package com.terry.proxy.plugin.socks5;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.socksx.v5.*;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * socks5 验证账号密码
 * @version 1.0
 * @author terry
 * @date 2023/2/10
 */
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class Socks5AuthHandler extends SimpleChannelInboundHandler<DefaultSocks5PasswordAuthRequest> {

    private String userName;
    private String password;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DefaultSocks5PasswordAuthRequest msg)  {
        //认证成功
        if (userName.equals(msg.username()) && password.equals(msg.password())) {
            Socks5PasswordAuthResponse passwordAuthResponse = new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS);
            ctx.writeAndFlush(passwordAuthResponse);
            ctx.pipeline().remove(this);
            ctx.pipeline().remove(Socks5PasswordAuthRequestDecoder.class);
            return;
        }
        log.info("认证失败");
        Socks5PasswordAuthResponse passwordAuthResponse = new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.FAILURE);
        // 发送鉴权失败消息，完成后关闭channel
        ctx.writeAndFlush(passwordAuthResponse).addListener(ChannelFutureListener.CLOSE);
    }
}
